/*
* @Author: xfy
* @Date:   2017-09-12 19:21:42
* @Last Modified by:   xfy
* @Last Modified time: 2017-09-14 15:16:59
*/
require('./index.css');
require('page/common/admin-nav-top/index.js');
var _supper         = require('util/supper.js');
var _adminProduct   = require('service/admin-product-service.js');
var _categoryManage = require('service/admin-category-service.js');
var templateIndex   = require('./index.string');
var templateAdd     = require('./add.string');

//page逻辑部分
var page = {
    res : {
        parentId : 0
    },
    init : function(){
        this.loadModal(0);
        this.bindEvent();
    },
    bindEvent : function(){
        var _this           = this;  
        //绑定查看子分类事件
        $(document).on('click', '.child-category-look', function(e){
            var $target = $(e.target);
            _this.hideModify();
            _this.loadModal($target.data('categoryId'));
        });
        //绑定返回上级品类事件
        $(document).on('click', '.category-back', function(){
            var categoryId = $('.category-parentId').text();
            _this.goCategoryId(categoryId);
        });
        //修改品类名称点击事件
        $(document).on('click', '.modify-category-name', function(e){
            var $name           = $(e.target).data('name'),
                $id             = $(e.target).data('id'),
                $categoryInfo   = $('.modify-categoryInfo');
                $categoryInfo.find('.category-id').text($id);
                //先清空一次输入框
                $categoryInfo.find('.category-name').val('');
                $categoryInfo.find('.category-name').attr('placeholder', $name);
                $categoryInfo.slideDown();
        });
        //修改品类的close按钮
        $(document).on('click', '.modify-categoryInfo .fa-close', function(){
            _this.hideModify();
        });
        //修改品类的确定按钮
        $(document).on('click', '.modify-categoryInfo .modify-btn', function(){
            var $categoryInfo   = $('.modify-categoryInfo');
                $id             = $categoryInfo.find('.category-id').text(),
                $name           = $categoryInfo.find('.category-name').val(),
                result          = _this.validata({
                    id          : $id,
                    name        : $name
                });
            //验证数据成功
            if(result.isTrue){
                _categoryManage.setCategoryName({
                    id : result.id,
                    name : result.name
                }, function(res){
                    _supper.successTips(res);
                    //成功时隐藏修改框
                    _this.hideModify();
                    _this.loadModal($('.category-parentId').text());
                }, function(errMsg){
                    _supper.errorTips(errMsg);
                });
            }
            else{
                _supper.errorTips(result.errMsg);
                return;
            }
        });
        //添加品类点击事件
        $(document).on('click', '.category-top .add-category-btn', function(){
            var categoryAddHtml = _supper.renderHtml(templateAdd, _this.res); 
            _this.$categoryCon.html(categoryAddHtml);
            _this.$categorySelect = _this.$categoryCon.find('.category-select');
            _this.loadCategory();
        });
        //品类的多级联动
        $(document).on('change', '.category-select', function(e){
            var $target = $(e.target);
            _categoryManage.getCategoryAndDeepChildrenCategroy($target.val() , function(res){
                //不同在于不选择完的分类也可以作为父类，用onSet获取到值
                $('.category-selects').find('.onSet').removeClass('onSet');
                $target.addClass('onSet');
                $('.onSet').nextAll().remove();
                if(res.length > 0){
                    _categoryManage.getChildrenParallelCategory($target.val(),function(res){
                        if(res.length > 0){
                            $target.after('<select class="category-select category-on"></select>');
                            $target.next().html(_this.getSelectOption(res));
                            $target.next().removeClass('category-on');
                        }
                    }, function(errMsg){
                        _supper.errorTips(errMsg);
                    });
                }

            }, function(errMsg){
                _supper.errorTips(errMsg);
            });
        });
        //从品类添加返回，并展示原来的页面
        $(document).on('click', '.category-add-back', function(){
            var categoryId = $('.category-add-back').data('categoryBackId');
            _this.goCategoryId(categoryId);
        });

        //品类添加的提交，先进行参数验证
        $(document).on('click', '.category-add-commit', function(){
            var categoryName    = $('.add-item-input').val(),
                $selectOption   = $('.category-selects .onSet'),
                parentId        = $selectOption.find('option:selected').val() || 0;
                //如果包含parent，则选择为所有类
                if($selectOption.hasClass('parent') && parentId == -1){
                    parentId = 0;
                }
                //如果为-1则取上一级分类的值
                else if(parentId == -1){
                    parentId = $selectOption.prev().find('option:selected').val();
                }
                result          = _this.validata({
                    name        : categoryName,
                    parentId    : parentId
            });
            //验证通过，添加品类
            if(result.isTrue){
                _categoryManage.addCategory({
                    name        : result.name,
                    parentId    : result.parentId
                }, function(res){
                    _supper.successTips(res);
                    window.setTimeout(function(){
                        window.location.href = './admin-category-manage.html';
                    }, 1000);
                },function(errMsg){
                    _supper.errorTips(errMsg);
                });
            }
            //验证不通过
            else{
                _supper.errorTips(result.errMsg);
                return;
            }
        });
    },
    //加载品类的信息
    loadModal : function(categoryId){
        var _this           = this,
            $categoryCon    = $('.category-con');
        this.$categoryCon = $categoryCon;
        _categoryManage.getChildrenParallelCategory(categoryId, function(res){
            //如果长度为零，说明没有子分类。
            if(res.length === 0){
                _supper.errorTips('该分类暂无子分类');
                return;
            }
            _this.res = res;
            var list = {
                data : res
            },
                htmlModal = _supper.renderHtml(templateIndex, list);
            $categoryCon.html(htmlModal);
        }, function(errMsg){
            _supper.errorTips(errMsg);
        });
    },
    //参数验证
    validata : function(data){
        var result = {
            isTrue : false
        };
        result.id       = data.id || 0;
        result.name     = data.name || '';
        result.parentId = data.parentId || 0;

        if(result.name === ''){
            result.errMsg = '品类名称不能为空';
            return result;
        }
        else if(result.parentId === -1){
            result.errMsg = '请选择完整的分类';
            return result;
        }

        result.isTrue = true;
        return result;
    },
    //隐藏修改品类名称框
    hideModify : function(){
        $('.modify-categoryInfo').slideUp();
    },
    //获取select框的选项，输入的是数组:输出的是html
    getSelectOption : function(optionArray){
        var html = '<option value="-1">-- 请选择 --</option>';
        for(var i = 0, length = optionArray.length; i < length; i++){
            html += '<option value="' + optionArray[i].id + '">' + optionArray[i].name + '</option>'
        }
        return html;
    },
    //第一次加载品类
    loadCategory : function(){
        var _this = this;
        _categoryManage.getChildrenParallelCategory(0, function(res){
            _this.$categorySelect.html(_this.getSelectOption(res));
        }, function(errMsg){
            _supper.errorTips(errMsg);
        });
    },
    //通过品类id进入展示子品类页面
    goCategoryId : function(categoryId){
        var _this = this;
        _categoryManage.getCategory(categoryId, function(res){
            _this.res.parentId = res.parentId;
            _this.loadModal(res.parentId);
        }, function(errMsg){
            _this.$categoryCon.html('<div class="error-tip"><p class="error-msg"><i class="fa fa-coffee"></i> 好像出错了哦…</p></div>');
        });
    }
};
$(function(){
    page.init();
});